package com.dd.admin.controller.system;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.common.aspect.annotation.LogOperation;
import com.dd.common.dto.system.job.SysJobDTO;
import com.dd.common.dto.system.job.SysJobQueryDTO;
import com.dd.common.entity.SysJob;
import com.dd.common.pojo.dto.IdsDTO;
import com.dd.common.pojo.dto.PageDTO;
import com.dd.common.pojo.dto.group.CreateGroup;
import com.dd.common.pojo.dto.group.UpdateGroup;
import com.dd.common.service.SysJobService;
import com.dd.common.utils.AjaxResult;
import com.dd.common.utils.PageResult;
import com.dd.common.validator.annotation.IDMust;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@SaIgnore
@Validated
@Tag(name = "定时任务", description = "定时任务管理接口")
@RestController
@RequestMapping("/sys/job")
public class SysJobController {

    @Autowired
    private SysJobService sysJobService;

    @LogOperation(title = "定时任务新增")
    @Operation(summary = "定时任务新增", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "定时任务新增参数",
            required = true,
            content = @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = SysJobDTO.class)
            )
    ))
    @PostMapping("/add")
    public AjaxResult<Boolean> add(@Validated(CreateGroup.class) @RequestBody SysJobDTO dto) {
        SysJob job = new SysJob();
        BeanUtils.copyProperties(dto, job);
        return AjaxResult.success(sysJobService.save(job));
    }

    @LogOperation(title = "定时任务编辑")
    @Operation(summary = "定时任务编辑", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "定时任务编辑参数",
            content = @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = SysJobDTO.class)
            )
    ))
    @PatchMapping("/edit")
    public AjaxResult<Boolean> edit(@Validated(UpdateGroup.class) @RequestBody SysJobDTO dto) {
        SysJob job = new SysJob();
        BeanUtils.copyProperties(dto, job);
        return AjaxResult.success(sysJobService.updateById(job));
    }

    @LogOperation(title = "定时任务删除")
    @Operation(summary = "定时任务删除", parameters = @Parameter(name = "id", description = "任务ID", in = ParameterIn.PATH))
    @DeleteMapping("/delete/{id}")
    public AjaxResult<Boolean> delete(@PathVariable @IDMust Long id) {
        return AjaxResult.success(sysJobService.removeById(id));
    }

    @LogOperation(title = "定时任务批量删除")
    @Operation(summary = "定时任务批量删除", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "定时任务批量删除参数",
            content = @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = IdsDTO.class)
            )
    ))
    @DeleteMapping("/batchDelete")
    public AjaxResult<Boolean> batchDelete(@Validated @RequestBody IdsDTO dto) {
        return AjaxResult.success(sysJobService.removeByIds(dto.getIds()));
    }

    @Operation(summary = "定时任务详情", parameters = @Parameter(name = "id", description = "任务ID", in = ParameterIn.PATH))
    @GetMapping("/detail/{id}")
    public AjaxResult<SysJob> detail(@PathVariable @IDMust Long id) {
        return AjaxResult.success(sysJobService.getById(id));
    }

    @Operation(summary = "定时任务分页列表")
    @GetMapping("/page")
    public AjaxResult<PageResult<SysJob>> page(@Validated PageDTO pageDTO, @Validated SysJobQueryDTO dto) {
        Page<SysJob> page = Page.of(pageDTO.getCurrent(), pageDTO.getSize());
        LambdaQueryWrapper<SysJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(dto.getJobName()), SysJob::getJobName, dto.getJobName())
                .like(StringUtils.hasText(dto.getJobGroup()), SysJob::getJobGroup, dto.getJobGroup())
                .eq(dto.getConcurrent() != null, SysJob::getConcurrent, dto.getConcurrent())
                .eq(dto.getMisfirePolicy() != null, SysJob::getMisfirePolicy, dto.getMisfirePolicy())
                .eq(dto.getStatus() != null, SysJob::getStatus, dto.getStatus())
                .orderByAsc(SysJob::getId);
        IPage<SysJob> result = sysJobService.page(page, queryWrapper);
        return AjaxResult.success(PageResult.iPageHandle(result.getTotal(), result.getCurrent(), result.getSize(), result.getRecords()));
    }

    @LogOperation(title = "定时任务状态更改")
    @Operation(summary = "定时任务状态更改",
            parameters = {
                    @Parameter(name = "id", description = "任务ID", in = ParameterIn.PATH),
                    @Parameter(name = "status", description = "状态值(0-暂停, 1-正常)", in = ParameterIn.PATH)
            })
    @PostMapping("/changeStatus/{id}/{status}")
    public AjaxResult<Boolean> changeStatus(@PathVariable Long id, @PathVariable Integer status) {
        SysJob sysJob = new SysJob();
        sysJob.setId(id);
        sysJob.setStatus(status);
        return AjaxResult.success(sysJobService.updateById(sysJob));
    }

    @LogOperation(title = "立即执行定时任务")
    @Operation(summary = "立即执行定时任务", parameters = @Parameter(name = "id", description = "任务ID", in = ParameterIn.PATH))
    @PostMapping("/run/{id}")
    public AjaxResult<Boolean> run(@PathVariable @IDMust Long id) {
        // 这里应该调用定时任务执行逻辑
        // 由于具体实现涉及定时任务调度框架，这里仅做示意
        return AjaxResult.success(true);
    }
}
